package org.libermundi.theorcs.chronicles.tapestry.components.ui;

import java.util.List;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.libermundi.theorcs.chronicles.dto.ChronicleSettings;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.chronicles.services.PersonaManager;
import org.libermundi.theorcs.core.tapestry.services.assets.AssetServices;
import org.libermundi.theorcs.security.services.SecurityManager;

public class PersoSwitcher {
	@Persist
	private List<Persona> _persos;
	
	@Inject
	@Path("${layout.images}/avatar/avatar250.png")
	private Asset _defaultAvatar;

	@SessionState
	private ChronicleSettings _chronicleSettings;
	
	@Inject
	private PersonaManager _personaManager;
	
	@Inject
	private SecurityManager _securityManager;
	
	@Inject
	private AssetServices _assetServices;	
	
	@SetupRender
	public void setupRender(){
		if(_persos == null || _persos.isEmpty()){
			_persos = _personaManager.getAllPersona(_securityManager.getCurrentUser(), _chronicleSettings.getChronicle());
		}
	}
	
	public String getPersonaName(){
		return _chronicleSettings.getPersona().getName();
	}
	
	public Asset getPersonaPicture(){
		String pict = _chronicleSettings.getPersona().getPicture();
		
		return _assetServices.getAsset(pict, _defaultAvatar);
	}
	
	public boolean isCanSwitch(){
		return (_persos.size() > 1);
	}
	
	@OnEvent(value="previous")
	public void previousPersona(){
		switchPersona(Boolean.FALSE);
	}

	@OnEvent(value="next")
	public void nextPersona(){
		switchPersona(Boolean.TRUE);
	}
	
	private void switchPersona(boolean forward){
		Persona currentPersona = _chronicleSettings.getPersona();
		Persona newPersona;
		int index = _persos.indexOf(currentPersona);
		if(index == 0 && !forward){ // Get previous persona
			newPersona = _persos.get(_persos.size()-1);
		} else if (index == _persos.size()-1 && forward) { // Get next persona ( ie : the first of the list )
			newPersona = _persos.get(0);
		} else {
			if(forward) {
				newPersona = _persos.get(index+1);
			} else {
				newPersona = _persos.get(index-1);
			}
		}
		_chronicleSettings.setPersona(newPersona);
	}
}
